//
//  SWHomeController.swift
//  SinaWeibo
//
//  Created by wszyxc on 16/7/17.
//  Copyright © 2016年 wszyxc. All rights reserved.
//

import UIKit
import MJRefresh

private let homeCellID = "homeCellID"



class SWHomeController: SWBaseController {
    
    //定义一个全局的数据源数组
    
    var homeGetDataViewModel = SWHomeGetDataViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()

        setupNav()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidDisappear(true)
        
        listView.mj_header.endRefreshing()
    }
    
    override func loadView() {
        
        if SWUserAcountViewModel.sharedUserAcountViewModel.isLogin{
            
            view = listView
            
            //1.将状态更新栏添加到tableView上
            //view.addSubview(stateBar)
            
            //2.将状态更新栏添加到navagationController的view上
            
            navigationController?.view.insertSubview(stateBar, belowSubview: (navigationController?.navigationBar)!)
 
            //使用下拉刷新控件
            setupRefreshHeader()
            
            //添加上啦刷新控件
            
            //            listView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: { () -> Void in
            //
            //                self.getNewData(true)
            //            })
            
            //获取首页数据
            homeGetDataViewModel.loadHomeData(false, isFinish: { (isSuc, messageCount) -> () in
                
                if isSuc{
                 //   print("刷新tableView")
                    self.listView.reloadData()
                 //   print("listView --- frame----\(self.listView.frame)")
                    
                }
                
            })
            
            
        }else{
            
            let visitorView = SWHomeVisitorView.homeVisitor()
            
            view = visitorView
            
            visitorView.closure = {
                
                print("执行了关注点击的闭包")
                let loginVC = SWLoginController()
                
                self.presentViewController(UINavigationController(rootViewController: loginVC), animated: true, completion: nil)
                
            }
        }
        
    }

    
    
    
    //懒加载tableView
    private lazy var listView:UITableView = {
        
        let tab = UITableView(frame: CGRectZero, style: .Plain)
        
        tab.dataSource = self
        
        tab.delegate = self
        
        tab.registerClass(SWHomeCell.self, forCellReuseIdentifier: homeCellID)
        
        tab.estimatedRowHeight = 200
        
   //     tab.rowHeight = 200
        
        tab.allowsSelection = false
        
        tab.separatorStyle = .None
        
       
        return tab
    }()
    
    
    
   private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch_highlighted", title: nil, target: self, action: nil)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop_highlighted", title: nil, target: self, action: "scanClick")
        
    
        navigationItem.titleView = navBtn

    }
    
    
    //懒加载按钮
    private lazy var navBtn:SWTitleButton = {
        
        let btn:SWTitleButton = SWTitleButton()
        
        btn.setTitle("\(SWUserAcountViewModel.sharedUserAcountViewModel.getUserAcount()?.name ?? "用户名")", forState: .Normal)
        
        btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
        
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        
        btn.setImage(UIImage(named: "navigationbar_arrow_down"), forState: .Normal)
        
        btn.setImage(UIImage(named: "navigationbar_arrow_up"), forState: .Selected)
        
        btn.sizeToFit()
        
        btn.addTarget(self, action: "navBtnClick", forControlEvents: .TouchUpInside)
        
        return btn

    }()
    
    @objc private func navBtnClick(){
        
        //1修改箭头方向
        navBtn.selected = !navBtn.selected
 
        //2弹出菜单
        let menuVC = SWMenuViewController.menuViewVC()
        
        //2.1设置转场动画代理
        menuVC.transitioningDelegate = self
        
        //2.2设置转场动画为自定义
        menuVC.modalPresentationStyle = .Custom
        
        //弹出
        presentViewController(menuVC, animated: true) { () -> Void in
            
        }
        
    }
    
    @objc private func scanClick(){
        
        print("二维码扫描")
        
     
        presentViewController(UINavigationController(rootViewController: SWScanController()), animated: true, completion: nil)
        
    }
    
    private lazy var refreshHeader:SWRefresh = SWRefresh()
    
    
    //添加下拉刷新
    private func setupRefreshHeader(){
 
        let header = MJRefreshNormalHeader { () -> Void in
            //获取新数据
            self.getNewData(false)
        }
        
        //设置文字
        header.setTitle("下拉刷新", forState: MJRefreshState.Idle)
        header.setTitle("松开刷新", forState: .Pulling)
        header.setTitle("刷新中", forState: .Refreshing)
        
        //设置字体
        header.stateLabel?.font = UIFont.systemFontOfSize(15)
        //设置颜色
        header.stateLabel?.textColor = UIColor.whiteColor()
        
        //隐藏刷新时间的label
        header.lastUpdatedTimeLabel?.hidden = true
        
        header.backgroundColor = THEMECOLOR
        //自动透明度
        header.automaticallyChangeAlpha = true

        //设置刷新控件
        listView.mj_header = header

        //开始刷新
        listView.mj_header.beginRefreshing()
        
    }
    
    


    //刷新
    private func getNewData(isPullUp:Bool){
        
        homeGetDataViewModel.loadHomeData(isPullUp) { (isSuc, messageCount) -> () in

            if isSuc{
                print("刷新tableView")
                self.listView.reloadData()
                
               //结束刷新
                self.listView.mj_header.endRefreshing()
        
                
                if messageCount>=0{
                    
                    //设置 加载多少条的动画
                    self.setStateBarAnima(messageCount)
                }
                

            }
        }
    }
    
    //设置刷新状态栏的动画的
    private func setStateBarAnima(count:Int){
    
        if stateBar.hidden == false{
            return
        }
        // 显示空间
        stateBar.hidden = false
        var name = ""
        if count == 0 {
            name = "当前没有更新,请稍后再试"
        }else {
            name = "本次刷新了\(count)条微博"
        }
        
        stateBar.stateLabel.text = name
        
        UIView.animateWithDuration(0.2,delay: 0, options: [], animations: { () -> Void in
            
            self.stateBar.transform = CGAffineTransformMakeTranslation(0, 30)
            
            }) { (_) -> Void in
                
                
                UIView.animateWithDuration(0.2, delay: 0.5, options: [], animations: { () -> Void in
                    
                    self.stateBar.transform = CGAffineTransformIdentity
                    
                    }, completion: { (_) -> Void in
                        
                        self.stateBar.hidden = true
                        
                })
        }
    
    }
    
    
    //懒加载添加刷新状态栏
    
    private lazy var stateBar:SWRefreshStateBarView = SWRefreshStateBarView(frame: CGRectMake(0, 64-30, ScreenWidth, 30))

}


// MARK: - tableView的数据源和代理
extension SWHomeController:UITableViewDataSource,UITableViewDelegate{
    
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
      //  print(homeGetDataViewModel.originalViewModelArr.count)
        
        return homeGetDataViewModel.originalViewModelArr.count ?? 0
        

    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(homeCellID, forIndexPath: indexPath) as! SWHomeCell
        
        cell.originalViewModel = homeGetDataViewModel.originalViewModelArr[indexPath.row]
        
        
        
     //   cell.backgroundColor = RandomColor()
        
        return cell
    }
    
    
}







// MARK: - 转场动画代理
extension SWHomeController:UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning{
    
    func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController?{
        
        //需要返回一个UIPresentationController
        
     
        return SWPresentationController(presentedViewController: presented, presentingViewController: presenting)
   
    }
    
   
    
    //返回执行动画的对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning?{
        
        isAnima = true
        return self
    }
    
    //返回消失动画的对象
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?{
        
        
        isAnima = false
        return self
    }
    
    
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        
        return 1
    }
    //自定义转场动画,弹出和消失都在这里执行
    func animateTransition(transitionContext: UIViewControllerContextTransitioning){
        
        //拿到toView 和 fromView
        
        if isAnima{

            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
            
            //使得一开始cover从最上面出来,表示缩放系数
            toView.transform = CGAffineTransformMakeScale(1.0, 0.0)
            
        //    print("toView---\(toView)")
            
            // 注意: 一定要将视图添加到容器上
            transitionContext.containerView()?.addSubview(toView)
            
            // 设置锚点
            toView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
            
            // 2.执行动画
            UIView.animateWithDuration(0.5, animations: { () -> Void in
                // 2.1清空transform
                toView.transform = CGAffineTransformIdentity
                }) { (_) -> Void in
                    // 2.2动画执行完毕, 一定要告诉系统
                    // 如果不写, 可能导致一些未知错误
                    transitionContext.completeTransition(true)
                    
                    
            }
            
        }else{
            
            print("隐藏菜单")
            
            let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)
            
         //   print("fromView---\(fromView)")
            
            UIView.animateWithDuration(0.2, animations: { () -> Void in
                // 注意:由于CGFloat是不准确的, 所以如果写0.0会没有动画
               
                fromView?.transform = CGAffineTransformMakeScale(1.0, 0.000001)
                }, completion: { (_) -> Void in
                    // 如果不写, 可能导致一些未知错误
                    transitionContext.completeTransition(true)
            })

            
            
        }
        
        
    }
    
}






